
var GameState = require("gameState");
var helpers = require('helperMe');

/**
 * 游戏背景类
 * 提供update和render函数实现无限滚动的背景功能
 */

cc.Class({
  extends: cc.Component,

  properties: {

    screenWidth: 960,
    screenHeight: 640,
    top: 0,
    state: GameState.STOP,
    speed: 0,

    node1: {
      default: null,
      type: cc.Node
    },
    node2: {
      default: null,
      type: cc.Node
    },

    node1Sprite: {
      default: null,
      type: cc.Sprite
    },

    node2Sprite: {
      default: null,
      type: cc.Sprite
    },

  },

  // use this for initialization
  onLoad: function () {
    var screen = cc.view.getVisibleSize();
    this.screenWidth = screen.width;
    this.screenHeight = screen.height;
    this.node2.y = this.node1.y + this.screenHeight;
    this.upNode = this.node1;
    this.downNode = this.node2;
    this.stop();

    this.bkspriteFrame1 = this.node1Sprite.spriteFrame;
    this.bkspriteFrame2 = this.node2Sprite.spriteFrame;
  },

  // called every frame
  update: function (dt) {

    //游戏进行中，则更新背景图片
    if (this.state == GameState.RUNNING) {
      var distance = this.speed * dt;
      this.node1.y -= distance;
      this.node2.y -= distance;

      if(this.downNode.y < -this.screenHeight){
        this.downNode.y = this.upNode.y + this.screenHeight;
        if (this.node1.y < this.node2.y) {
          this.upNode = this.node2;
          this.downNode = this.node1;
        }else{
          this.upNode = this.node1;
          this.downNode = this.node2;
        }
      }
    }

  },

  // 开始
  running: function (speed) {
    this.state = GameState.RUNNING;
    this.setSpeed(speed);
    
    //随机地图
    var randomIdx = helpers.getRandomInt(0, 2);
    if(randomIdx == 0){
      this.node1Sprite.spriteFrame = this.bkspriteFrame1;
      this.node2Sprite.spriteFrame = this.bkspriteFrame1;
    }else {
      this.node1Sprite.spriteFrame = this.bkspriteFrame2;
      this.node2Sprite.spriteFrame = this.bkspriteFrame2;
    }
  },

  // 暂停
  pause: function () {
    this.state = GameState.PAUSE;
  },

  // 恢复
  continue: function () {
    this.state = GameState.RUNNING;
  },

  // 停止
  stop: function () {
    this.state = GameState.STOP;
  },

  // 加速
  addSpeed: function (value) {
    this.speed += value;
  },

  // 减速
  substractSpeed: function (value) {
    this.speed -= value;
    if (this.speed < 0) {
      this.speed = 0;
    }
  },

  // 设置速度
  setSpeed: function (value) {
    // //cc.log("scenecontroller setSpeed : " + value);
    this.speed = value;
  },

  // 设置阶段
  setStageInfo: function (stageInfo) {
    this.stageInfo = stageInfo;
  },


  // // 恢复默认速度
  // recoverDefaultSpeed: function(value){
  //   this.speed = defaultSpeed;
  // },
});

